<script lang="ts" setup>
import { ref } from 'vue'

import { useVbenModal } from '@vben/common-ui'

import { message } from 'ant-design-vue'

import { useVbenForm } from '#/adapter/form'
import { fastAdd, userCategorys } from '#/api/goods'

const emit = defineEmits(['refresh'])
const categorysList = ref([])
const [Form, formApi] = useVbenForm({
  handleSubmit: onSubmit,
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'template_no',
      label: '简码',
    },
    {
      component: 'Select',
      fieldName: 'data_type',
      label: '归属品类（群）',
      rules: 'required',
      componentProps: {
        allowClear: true,
        filterOption: (input, option) => {
          return (option?.label || '').toLowerCase().includes(input.toLowerCase())
        },
        options: categorysList,
        showSearch: true,
      },
    },
  ],
  showDefaultActions: false,
})
const category_id_one = ref('')
const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  onCancel() {
    modalApi.close()
  },
  onConfirm: async () => {
    await formApi.validateAndSubmitForm()
  },
  onOpenChange(isOpen: boolean) {
    if (!isOpen) return
    const { data } = modalApi.getData<Record<string, any>>()
    category_id_one.value = data

    const parmas = {
      limit: 30,
      is_remote: true,
      page: 1,
      select: true,
    }
    userCategorys(parmas).then((res) => {
      categorysList.value = res.list.map((item: any) => ({
        label: item.name,
        value: item.id,
      }))
    })
  },
  title: '添加简码',
})

function onSubmit(values: Record<string, any>) {
  modalApi.lock()
  const data = values
  if (data.template_no === undefined) {
    data.template_no = ''
  }
  const parmas = {
    formData: {
      ...data,
      category_id_one: category_id_one.value,
    },
  }
  fastAdd(parmas).then((res: any) => {
    modalApi.unlock()
    if (res.data.code === 1) {
      message.success(res.data.msg)
      emit('refresh', res.data.data)
      modalApi.close()
    } else {
      message.error(res.data.msg)
    }
  })
}
</script>
<template>
  <Modal>
    <Form />
  </Modal>
</template>
